<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>chat</h1>
    <input type="text" />
    <button>发送</button>
    <select name="" id="chat_sel"></select>
    <script>
      const btn = document.querySelector("button");
      const ipt = document.querySelector("input");
      // 定义和后端一样的类型
      const msgType = {
        chatError: 0,
        chatList: 1,
        chatGroup: 2,
        singleChat: 3,
      };

      // 连接服务器
      const ws = new WebSocket(
        `ws://localhost:3001?token=${localStorage.getItem("token")}`
      );
      ws.onmessage = (msg) => {
        service(msg);
      };
      ws.onerror = () => {
        console.log("错误了");
      };
      ws.onopen = () => {
        console.log("连接了");
      };
      // 处理回来的数据
      function service(msg) {
        msg = JSON.parse(msg.data);
        switch (msg.type) {
          // 处理 错误
          case msgType.chatError:
            localStorage.removeItem("token");
            location.href = "/login";
            break;
          // 渲染列表
          case msgType.chatList:
            chat_sel.innerHTML =
              `<option value="all">all</option>` +
              msg.data
                .map(
                  (item) => `
               <option value="${item}">${item}</option>
            `
                )
                .join("");
            break;
          // 处理群聊除了自己都要发送
          case msgType.chatGroup:
            console.log(msg.user, msg.data.data ? msg.data.data : msg.data);
            break;
          // 处理私聊
          case msgType.singleChat:
            console.log(msg.user, msg.data);
            break;
          default:
            break;
        }
      }
      // 点击发送数据
      btn.onclick = () => {
        // 群发
        if (chat_sel.value === "all") {
          ws.send(createMsg(msgType.chatGroup, ipt.value));
          // 私聊
        } else {
          ws.send(createMsg(msgType.singleChat, ipt.value, chat_sel.value));
        }
      };
      function createMsg(type, data, to) {
        return JSON.stringify({
          type,
          data,
          to,
        });
      }
    </script>
  </body>
</html>
